<?php

namespace common\service;

use common\model\StatusModel;
use common\model\TaskMemberModel;
use common\model\TaskWorkOrderModel;
use support\EntityTaskFilterParser;
use support\SingletonTrait;


class TaskLibraryTaskMemberService
{
    use SingletonTrait;
    use EntityTaskFilterParser;

    /**
     * 成员用户任务列表
     * @param $param
     * @param $page
     * @return array
     */
    public function getTaskIdList($param, $page): array
    {
        if (empty($param['filter'])) {
            return [];
        }
        $filter = $param['filter'];
        $fields = $param['fields'] ?? ['task_member.task_id'];
        $taskMemberList = model(TaskMemberModel::class);
        // 如果filter条件有task_work_order条件
        if (isset($filter['task_work_order.status'])) {
            $taskMemberList = $taskMemberList->join('task_work_order on task_work_order.task_id = task_member.task_id');
        }

        $filter = [$filter, ['task.tenant_id' => \request()->getTenantId()]];
        $taskMemberList = $taskMemberList->join('task on task.id = task_member.task_id')
            ->where(parse_filter_to_tp_where($filter, 'task'))
            ->field($fields)
            ->page(...$page)
            ->select();
        if (empty($taskMemberList)) {
            return [];
        }

        return $taskMemberList;
    }

    /**
     * 获取与我相关的统计数量
     * 通过前端传过来的code+筛选条件筛选与我相关的数据
     * @param string $code 前端权限CODE【我创建的,我分配的,我负责的,我参与的】
     * @param array $filter 筛选条件 【项目,集,环节工序,搜索....】
     * @param array $page
     * @return array ["count":"数量，最多不超过100个"]
     */
    public function getTaskMemberCount(string $code = '', array $filter = [], array $page = [0, 100]): array
    {
        $returnData = [
            'count' => 0
        ];
        if (empty($filter)) {
            return [];
        }
        $filterByCode = $this->getFilterByCode($code);
        $fields = "distinct task.id";
        $taskMemberModel = model(TaskMemberModel::class);
        $taskMemberList = $taskMemberModel->join('task on task.id = task_member.task_id')
            ->where($filter)
            ->where($filterByCode)
            ->field($fields)
            ->limit(...$page)
            ->select();
        $returnData['count'] = count($taskMemberList);
        return $returnData;
    }

    /**
     * 通过code 找到对应 where 条件
     * @param string $code
     * @return array 【"project_id":22,"step_category_id":2】
     */
    public function getFilterByCode(string $code): array
    {
        $userId = \request()->getUserId();
        $codeMap = [
            'me_created' => ['task.created' => $userId], // 我创建的
            'me_assigned' => ['task.assignee' => $userId], // 我分配的
            'me_fz' => ['task_member.user_id' => $userId], // 我负责的
            'me_cy' => ['task_member.partner' => $userId] // 我参与的
        ];
        return $codeMap[$code] ?? [];
    }


}
